import { DBCommonType } from '../types/db';
import connection from './index';

export function convertParams(obj: DBCommonType): string {
  const keys = Object.keys(obj);
  // const values = Object.values(params).toString();
  // key=value,key=value
  return keys
    .map((item) => {
      return `${item} = "${obj[item]}"`;
    })
    .join(',');
}

export function convertWhere(where: DBCommonType): string {
  const keys = Object.keys(where);
  // const values = Object.values(params).toString();
  // key=value,key=value
  return keys
    .map((item) => {
      return `${item} = "${where[item]}"`;
    })
    .join(' AND ');
}
// sql语句 : 麻烦
export async function insert(tableName: string, params: DBCommonType) {
  // 1. 取出params里面的key和value
  // {name : 'zhangsan',age:20}
  const keys = Object.keys(params).toString();
  const values = Object.values(params).toString();
  const sql = `insert into ${tableName} (${keys}) values ('${values}')`;
  return await query(sql);
}
// person 表名  insert into 表名 ('name', 'age') values ('张三',20)
// await ctx.db.insert('person', {name:'zhangsan'})
// update 表名 set username=''
// {id:2 , id : 4}  => id = 2 AND id = 4
export async function update(
  tableName: string,
  params: DBCommonType,
  where: DBCommonType
) {
  const convertStr = convertParams(params);
  return await query(
    `update ${tableName} set ${convertStr} where ${convertWhere(where)}`
  );
}

export async function deletes(tableName: string, where: DBCommonType) {
  return await query(`delete from ${tableName} where ${convertWhere(where)}`);
}
// where id > 10 and id < 30
export async function select(
  tableName: string,
  where: DBCommonType,
  keys: string[]
) {
  let newKeys = '';
  if (keys.length !== 0) {
    newKeys = keys.join(',');
  } else {
    newKeys = '*';
  }
  let sql = `select ${newKeys} from ${tableName}`;
  if (JSON.stringify(where) !== '{}') {
    sql += ` where ${convertWhere(where)}`;
  }
  console.log(sql);
  return await query(sql);
}

export async function query(sql: string) {
  return await new Promise((resolve, reject) => {
    connection.query(sql, function (err, result) {
      if (err != null) {
        // 抛出一个错误
        reject(err);
        throw new Error(String(err));
      }
      resolve(result);
    });
  });
}

// query('select * from home')
